package com.michael.retail.auth.exception;

import com.michael.retail.commons.pojo.global.R;
import com.netflix.client.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 类功能描述:
 * <pre>
 *   认证异常处理器
 * </pre>
 *
 * @author Michael
 * @version 1.0
 * @date 2021/7/6 19:22
 */
@Slf4j
@RestControllerAdvice
public class AuthExceptionHandler {

    /**
     * 用户名和密码错误
     */
    @ExceptionHandler(InvalidGrantException.class)
    public R handleInvalidGrantException(InvalidGrantException e) {
        return R.failed("用户名或者密码错误");
    }

    /**
     * 用户不存在
     * PS: 这个异常默认被拦截处理了,不会到这里
     */
    @ExceptionHandler(UsernameNotFoundException.class)
    public R handleUsernameNotFoundException(UsernameNotFoundException e) {
        return R.failed("不存在的用户");
    }

    /**
     * 账户异常(禁用、锁定、过期)
     */
    @ExceptionHandler({InternalAuthenticationServiceException.class})
    public R handleInternalAuthenticationServiceException(InternalAuthenticationServiceException e) {
        return R.failed(e.getMessage());
    }


    @ExceptionHandler({NoHandlerFoundException.class})
    public R handNoHandlerFoundException(NoHandlerFoundException e) {
        return R.failed("404");
    }

    @ExceptionHandler({OAuth2Exception.class})
    public R handOAuth2Exception(OAuth2Exception e) {
        e.printStackTrace();
        return R.failed(e.getMessage());
    }

    @ExceptionHandler({ClientException.class})
    public R handleClientException(ClientException e) {
        e.printStackTrace();
        return R.failed(e.getMessage());
    }

    @ExceptionHandler({Exception.class})
    public R handException(Exception e) {
        e.printStackTrace();
        return R.failed(e.getMessage());
    }
}
